const express = require('express')
const app = express()
const path = require('path')
const bodyParser = require('body-parser')
const config = require('./config/production')
const superagent = require('superagent')
const cheerio = require('cheerio')
var log4 = require('./tools/logs')
app.use(bodyParser())

// app.all('*', function (req, res, next) {
//     res.header("Access-Control-Allow-Origin", "*")
//     res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With")
//     res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
//     res.header("X-Powered-By", ' 3.2.1')
//     if (req.method == "OPTIONS") res.send(200)
//     else next()
// })

app.use(express.static(path.join(__dirname, './static')))

app.get('/api/v1/get_tgdz',function(req,res){
    var data_ym = req.query.data_ym || ''
    var data_d = req.query.data_d || ''
    log4.logs('打印接口 /api/v1/get_tgdz 入参')
    log4.logs(data_ym+','+data_d)
    if(data_ym=='' || data_d==''){
        res.send({
            code:'201',
            msg:'参数错误'
        })
        return;
    }
    try{
        var req_url = 'https://wannianrili.51240.com/ajax/'
        superagent.get(req_url)
        .query({q:data_ym},{v:'18121802'})
        .set({'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'})
        .end(function (err, rest) {
            // 抛错拦截
            if (err) {
                log4.logs('请求接口网络错误')
                log4.logs(err)
            }
            let $ = cheerio.load(rest.text)
            var data_d_s = parseInt(data_d) - 1
            var result =  $('#wnrl_k_you_id_'+data_d_s).find('.wnrl_k_you_id_wnrl_nongli_ganzhi').text()
            res.send({
                code:'200',
                data:result
            })
        })
    }catch(err){
        log4.logs(err)
        res.send({
            code:'202',
            msg:'网络繁忙！请稍后再试'
        })
    }
})

function s(){
    var req_url = ''
    superagent.get(req_url)
    .query({q:data_ym},{v:'18121802'})
    .set({'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'})
    .end(function (err, rest) {
        // 抛错拦截
        if (err) {
            log4.logs('请求接口网络错误')
            log4.logs(err)
        }
        let $ = cheerio.load(rest.text)
        var data_d_s = parseInt(data_d) - 1
        var result =  $('#wnrl_k_you_id_'+data_d_s).find('.wnrl_k_you_id_wnrl_nongli_ganzhi').text()
        res.send({
            code:'200',
            data:result
        })
    })
}


app.listen(config.port)
console.log('程序运行在' + config.port)